package cn.leedsoft.luma.plugins.spring;

import cn.leedsoft.luma.common.Constants;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Created by leeds on 2016/6/20.
 */
@Component
public class SpringHelper implements ApplicationContextAware{
    private static ApplicationContext cxt;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.cxt = applicationContext;
    }
    public static <T> T getBean(Class<T> requiredType) {
        cxt = getCxt();
        return cxt.getBean(requiredType);
    }

    private static ApplicationContext getCxt() {
        if(cxt == null) {
            System.setProperty("spring.profiles.active", "test");
            cxt = new ClassPathXmlApplicationContext(Constants.springContextConfigLocations);
        }
        return cxt;
    }
}
